﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using CommunicationDataContract;
using System.Threading;

namespace CommunicationServiceApplication
{
    public partial class WindowsServiceApplication : ServiceBase
    {
        private ServiceHost serviceHost;
        public WindowsServiceApplication()
        {

            InitializeComponent();
            WindowsServiceController.Instance.PropertyChanged += new PropertyChangedEventHandler(WindowsServiceController_Instance_PropertyChanged);
        }

        protected override void OnStart(string[] args)
        { 
            StartSeriveEndPoint();
            WindowsServiceController.Instance.IsWindowsServiceActive = true;
        }

        protected override void OnStop()
        {
            WindowsServiceController.Instance.IsWindowsServiceActive = false;
        }

        protected void WindowsServiceController_Instance_PropertyChanged(object sender, PropertyChangedEventArgs obj)
        {
            new Thread(new ThreadStart(() => { 
            if (obj.PropertyName == "IsWindowsServiceActive")
            {
                if (WindowsServiceController.Instance.IsWindowsServiceActive)
                    WindowsServiceController.Instance.LastAction = DateTime.Now;

                WindowsServiceController.Instance.NotifyAttachedApplicationsOfChange();
                GoBackToSleep();
            }
            })).Start();
        }

        private void GoBackToSleep()
        {
            if (WindowsServiceController.Instance.IsWindowsServiceActive)
            {
                WindowsServiceController.Instance.LastAction = DateTime.Now;
                System.Threading.Thread.Sleep(5000);
                GoBackToSleep();
            }
            else
            {
                WindowsServiceController.Instance.LastAction = default(DateTime);
            }
        }


        private void StartSeriveEndPoint()
        {
            if (serviceHost != null && serviceHost.State != CommunicationState.Opened)
                serviceHost = null;

            if (serviceHost == null)
            {
                try
                {
                    serviceHost = new ServiceHost(typeof(WindowsServiceCommunicationEndPoint));
                    NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                    serviceHost.AddServiceEndpoint(typeof(IWindowsServiceCommunicationEndPointContract), binding, EndpointSettings.WindowsServiceEndpointAddress);
                    serviceHost.Open();
                }
                catch (Exception ex)
                {
                    serviceHost = null;
                }
            }
        }
    }
}
